import getpath
import os
import openpyxl
from openpyxl.drawing.image import Image
import fitz
from pprint import pprint
from PyQt5 import QtWidgets
import fitz
import io
from PIL import Image as PILImage
from typing import Tuple
from bs4 import BeautifulSoup
doc=None
filename=None
curvePage=-1
def getimages():
    folder=os.path.split(os.path.abspath(filename))[0]
    pimgs=[]
    for one in doc.find_all("img"):
        print(one,dir(one))
        print(one.attrs["src"])
        pimgs.append(os.path.join(folder,one.attrs["src"]))
    return pimgs[1:]
def getimageTabls_raw():
    tbs=[]
    for one in doc.body.contents:
        # print(dir(one))    
        if one.name=="table":
            tbs.append(one)
    return tbs[2:-2]
def T(a):
    b=[]
    for i in range(len(a[0])):
        b.append([])
    for i in range(len(a)):
        one=a[i]
        for j in range(len(one)):#cell in one:
            b[j].append(one[j])
    return b
def addOne(data,one):
    if len(data)==0:#first
        r=one
    else:
        r=np.concatenate((data,one),axis=1)
    return r
 
def addOneAxis0(data,one):
    if len(data)==0:#first
        r=one
    else:
        r=data+one[1:]#remove first title row
    return r    
def getDataMass(file_name):
    global doc,filename
    filename=file_name
    fcontent=open(file_name,encoding="utf-8").read()
    doc = BeautifulSoup(fcontent,"html.parser")
    tbs=doc.find_all("table")#,attrs={"role":"grid"})
    r=[]
    table=tbs[-2]
    allr=table.find_all("tr")
    onerow=[]
    for col in allr[0].find_all('th'):
        onerow.append(col.text)
    r.append(onerow)
    for row in allr[1:]:
        onerow=[]
        for col in row.find_all('td'):
            onerow.append(col.text)
        r.append(onerow)
    return (r,[])
def mergeMass(data,mass):
    data[0].append("mass")
    data[0].append("volume")
    for one in data[1:]:
        (m,volume)=getMass(one[0],mass)
        one.append(m)
        one.append(volume)
    return data
def selectMass(data,mass):
    r=[("mass","volume")]
    for one in data[1:]:
        (m,volume)=getMass(one[0],mass)
        r.append((m,volume))
    return r
def getDataAndMass(fname):
    (data,mass)=getDataMass(fname)
    mass=selectMass(data,mass)
    return (data,mass)
def getMass(one,mass):
    one=one.replace("\n","")
    for m in mass:
        if len(m)>3 and  m[1]==one:
            return (m[2],float(m[3])*100)
    return ("","")
def output(ts,fname):
    f=open(fname,'w')
    for one in ts:
        line=",".join(one)
        line=line.replace("\n","")
        f.write(line+"\n")
    f.close()
def output_curve(ws,hang):#outputsheet,pdf filename,0-n page
    ts=getimageTables()
    outputImages(ts,ws,hang)
def outputImages(ts,ws,hang):#outputsheet,pdf filename,0-n page
    ss=QtWidgets.qApp.screens()
    if len(ss)<1:
        rowh=13.5/72.0*96
    else:
        rowh=13.5/72.0*ss[0].physicalDotsPerInch() #bang to pixel
    for i in range(len(ts)):
        (img,paras)=ts[i]
        folder=os.path.split(os.path.abspath(filename))[0]
        img = Image(os.path.join(folder,img))
        img.width=300#not too big
        img.height=200
        # print(dir(img))
        n=int((img.height)/rowh)
        at_row=i*n+hang
        for j in range(len(paras)):
            ws["A"+str(at_row+j)]=paras[j]
        ws.column_dimensions['A'].width = 30.0
        ws.add_image(img, "B"+str(at_row))  # 图片 插入 A1 的位置上
def test1():
    global filename
    filename=r"iCAP PRO\iCAP PRO.html"
    (data,mass)=getDataAndMass(filename)
    geti()
def getimageTables():
    tbs=[]
    for one in doc.body.contents:
        if one.name=="table":
            tbs.append(one)
    its=tbs[2:-2]
    r2=[]
    for one in its:
        r=getImageTable_row(one)
        for one in r:
            r2.append(one)
    return r2
def getImageTable_row(one):
    r=[]
    for t in one.find_all("table"):
        r.append(getImageTable_one(t))
    return r
def getImageTable_one(one):
    rows=one.find_all("tr")
    paras=[rows[0].text.replace("\n","")]
    for one in rows[2:]:
        paras.append(one.text.replace("\n",""))
    img=rows[1].find("img").attrs["src"]
    return(img,paras)
def geti():
    wb = openpyxl.Workbook()
    ws = wb.active
    output_curve()
    wb.save("imags.xlsx")
if __name__=="__main__":
    test1()
